<!--
* description: 备件借用归还
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="false"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
    >
      <template #returnQty="scope">
        <el-input
          :key="scope.col.prop"
          v-model="scope.row.returnQty"
          placeholder="请输入数量"
          clearable
          @change="numChange($event, scope.row, scope.col, scope.$index)"
        />
      </template>
    </one-table-template>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import Vue from "vue";
import api from "@/api/pa/apiBranchWarehouse";
import request from "@/utils/request";

export default {
  name: "partsBorrowingReturning",

  components: {
    OneTableTemplate,
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ""], function () {
      next();
    });
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);

    return {
      icon: "el-icon-arrow-down",
      status: false,
      editRowData: {},
      // 网格查询API配置对象
      apiConfig: api.partsBorrowingReturningGetDataD,
      // 动态组件-按钮
      tableButtons: [
        // {
        //   compKey: "btnKey1",
        //   type: "primary",
        //   size: "small",
        //   name: "search",
        //   clickEvent: () => this.queryTable(1),
        //   text: this.$t("sys.button.query"), // 查询
        //   position: "right",
        //   fuzzySearch: true,
        // },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          name: "reset",
          clickEvent: () => this.reset(),
          text: this.$t("sys.button.reset"),
          position: "right", // 重置
        },
        // {
        //   compKey: 'btnKey3',
        //   type: '',
        //   size: 'small',
        //   name: 'add',
        //   clickEvent: this.add,
        //   text: this.$t('sys.button.add'), // 新增
        //   position: 'left'
        // },
        {
          compKey: "btnKey3",
          type: "",
          size: "small",
          parentFileds: "disabled:table",
          clickEvent: () => this.save(),
          text: "保存", // 新增
          name: "adopt",
          position: "left",
        },
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              {
                compKey: "compKey1",
                labelName: "借件单号：",
                codeField: "borrowCode",
                component: () => import("@/components/pa/partsBorrowingReturning"),
                type: "inputText",
                isMust: true,
                span: 6,
              },
              {
                compKey: "compKey2",
                labelName: "仓库名称：",
                codeField: "warehouseId",
                textField: "warehouseName",
                customObj: {
                  api: api.queryWareHouse,
                  defOptionFields: ["warehouseId", "warehouseName"],
                },
                component: () => import("@/components/org/commonSelect"),
                type: "dropdownList",
                isMul: false,
                disabled: true,
                isMust: true,
              },
              {
                compKey: "compKey3",
                labelName: "借件人员：",
                codeField: "auditorId",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                disabled: true,
                isMust: true,
              },
              {
                compKey: "compKey4",
                labelName: "借件日期：",
                codeField: "applyDateStart,applyDateEnd",
                component: () =>
                  import("@/components/org/datePicker/datePicker.vue"),
                type: "daterange",

                disabled: true,
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey5",
                labelName: "联系电话：",
                codeField: "linkPhone",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                disabled: true,
                isMul: false,
                isMust: true,
              },
              {
                compKey: "compKey6",
                labelName: "VIN：",
                codeField: "vin",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                disabled: true,
                isMust: true,
              },
              {
                compKey: "compKey7",
                labelName: "品种数：",
                codeField: "partNum",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                disabled: true,
                isMust: true,
              },
              {
                compKey: "compKey8",
                labelName: "借件金额：",
                codeField: "lumpSum",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                disabled: true,
                isMust: true,
              },
              {
                compKey: "compKey9",
                labelName: "借件原因：",
                codeField: "borrowReason",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isMul: false,
                disabled: true,
                isMust: true,
              },
            ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "updateControlId",
                label: "并发控制ID",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "partId",
                label: "备件id",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "dlrId",
                label: "dlrId",
                hidden: true,
                alwaysHidden: true,
              },
              {
                prop: "partNo",
                label: "备件编号",
              },
              {
                prop: "partName",
                label: "备件名称",
              },

              // {
              //   prop: "partRepairType",
              //   label: "备件类别",
              // },
              {
                prop: "carConfigIdList",
                label: "适用车型",
              },
              // {
              //   prop: "",
              //   label: "备件属性",
              // },
              {
                prop: "",
                label: "SNP",
              },
              {
                prop: "borrowQty",
                label: "借件数量",
              },
              {
                prop: "pointPriceTax",
                label: "借件单价",
              },
              {
                prop: "debitamount",
                label: "借件金额",
              },
              {
                prop: "quantityReturned",
                label: "待归还数",
              },
              {
                prop: "returnQty",
                label: "归还数量+",
                isComponent: true,
                comps: [
                  {
                    compKey: "compKey5" + this.$utils.generateId(),
                    codeField: "returnQty",
                    component: () => import("@/components/org/commonInput"),
                    type: "inputText",
                  },
                ],
              },
              {
                prop: "unableReturnQty",
                label: "无法归还数+",
                isComponent: true,
                comps: [
                  {
                    compKey: "compKey5" + this.$utils.generateId(),
                    codeField: "unableReturnQty",
                    component: () => import("@/components/org/commonInput"),
                    type: "inputText",
                  },
                ],
              },
              {
                prop: "remark",
                label: "备注+",
                isComponent: true,
                comps: [
                  {
                    compKey: "compKey5" + this.$utils.generateId(),
                    codeField: "remark",
                    component: () => import("@/components/org/commonInput"),
                    type: "inputText",
                  },
                ],
              },
            ],
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          borrowId: "",
          borrowCode: "",
          warehouseId: '',
          warehouseName: "",
          auditorId: "",
          applyDateStart: "",
          applyDateEnd: "",
          vin: "",
          partNum: "",
          lumpSum: "",
          linkPhone: '',
          borrowReason: "",
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
    };
  },
  watch: {
    "formField.borrowId": {
       handler(val, old) {
        if (val != "" && val != old) {
           this.getInfo(val);
        }
      },
      deep: true,
    },
  },
  mounted() {
  },

  methods: {
    // purAmount = purQty * purPrice
    //quantityReturned =  returnQty + unableRerurnQty
    numChange(val, row, col, index) {
      const panter = /c|(^[1-9][0-9]*$)/
      if (!panter.test(val)) {
        row[col['prop']] = ''
        row['quantityReturned '] = '0.00'
        if (val) {
          this.$message('请输入正确的数量！')
        }
      } else if (Number(val) < Number(row['minPurchasePage'])) {
        row[col['prop']] = ''
        row['quantityReturned '] = '0.00'
        this.$message('不能小于最小订货量！')
      } else {

        this.$set(row, 'quantityReturned ', (Number(val) + Number(row['purPrice'])).toFixed(2))
      }

      this.totalType = this.$refs['multipleTable'].list.length
      this.totalAmount = this.$refs['multipleTable'].list.reduce((amount, row) => {
        return Number(amount) + (Number(row['purAmount']) || 0)
      }, 0).toFixed(2)
    },
    getInfo(val) {
      // request({
      //   url: api.partsBorrowingReturningGetDataM.APIUrl,
      //   method: "post",
      //   data: { borrowId: val },
      // }).then((res) => {
      //   if (res.result == "1") {
      //     this.formField = Object.assign(this.formField, res.rows[0]);
      //     this.queryTable(1)
      //   }
      // });
      this.queryTable(1)
    },
    // 保存
    save() {
      let parmasData = {};
      parmasData = { ...this.formField, paramList: this.$refs['multipleTable'].list};
      request({
        url: api.partsBorrowingReturningSave.APIUrl,
        method: "post",
        data: parmasData,
      }).then((res) => {
        if (res.result == "1") {
          this.$message.success(res.msg);
          this.reset()
          this.$refs['multipleTable'].queryTable();
        }else{
          this.$message.warning(res.msg)
        }
      });
    },
  },
};
</script>
<style lang='scss' scoped>
.red {
  background: red;
}
</style>
